package com.mingtu.guards.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.LRSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.AircraftRecordAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.AirRecordBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class AircraftDataAnalysisActivity extends MyBaseActivity {

    @BindView(R.id.tv_total_mileage)
    TextView tvTotalMileage;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.tv_total_count)
    TextView tvTotalCount;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private AircraftRecordAdapter aircraftRecordAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_aircraft_data_analysis;
    }

    @Override
    protected void initView() {
        setModuleTitle("数据分析");
    }

    @Override
    protected void initData() {
        String airName = getIntent().getStringExtra("airName"); //无人机名字

        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new BottomSpaceItemDecoration());
        recycler.addItemDecoration(new LRSpaceItemDecoration());

        aircraftRecordAdapter = new AircraftRecordAdapter();
        if(isOpenLoadAnimation){
            aircraftRecordAdapter.isFirstOnly(isFirstOnly);
            aircraftRecordAdapter.openLoadAnimation(animationType);
        }

        aircraftRecordAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(aircraftRecordAdapter);
        aircraftRecordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AirRecordBean.DataBean.ListBean listBean = aircraftRecordAdapter.getData().get(position);
                String vodeoUrl = listBean.getBackUrl();
                if (!StringUtils.isEmpty(vodeoUrl)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("vodeoUrl", vodeoUrl);
                    bundle.putString("title", airName);
                    bundle.putBoolean("shareFlag", true);
                    IntentUtils.getInstance().readyGo(AircraftDataAnalysisActivity.this, VideoPlayActivity.class, bundle);
                } else {
                    ToastUtils.showLong("未获取到直播链接地址~");
                }
            }
        });

    }

    @Override
    protected void getData() {
        getAirCountAll();
        getAirRecord(1);
        initListener();
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getAirRecord(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(aircraftRecordAdapter.getData(), Constant.PAGE_SIZE);
                    getAirRecord(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 飞行数据
     */
    private void getAirCountAll() {
        OkGo.<String>post(MyConstant.POST_AIR_COUNT_ALL)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {//{"msg":"success","code":0,"data":{"totalDuration":"8543","totalMileage":"1.03","totalCount":42}}
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                JSONObject dataObject = jsonObject.getJSONObject("data");
                                if (dataObject != null) {
                                    String totalDuration = dataObject.getString("totalDuration");
                                    String totalMileage = dataObject.getString("totalMileage");
                                    String totalCount = dataObject.getString("totalCount");

                                    if (!StringUtils.isEmpty(totalDuration)) {
                                        long d = 0;
                                        if (totalDuration.indexOf(".") != -1) {
                                            String array[] = totalDuration.split("\\.");
                                            d = Long.parseLong(array[0]);
                                        } else {
                                            d = Long.parseLong(totalDuration);
                                        }
                                        tvTotalTime.setText(MyUtills.formatSeconds2(d));
                                    } else {
                                        tvTotalTime.setText("0");
                                    }

                                    if (!StringUtils.isEmpty(totalMileage)) {
                                        tvTotalMileage.setText(totalMileage + "");
                                    }

                                    if (!StringUtils.isEmpty(totalCount)) {
                                        tvTotalCount.setText(totalCount + "");
                                    }
                                }


                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);

                    }
                });
    }


    /**
     * 临时任务列表
     */
    private void getAirRecord(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_AIR_RECORD)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            AirRecordBean airRecordBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                airRecordBean = new AirRecordBean();
                                airRecordBean = gson.fromJson(result, AirRecordBean.class);
                                List<AirRecordBean.DataBean.ListBean> dataBeans = airRecordBean.getData().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            aircraftRecordAdapter.replaceData(dataBeans);
                                        } else {
                                            aircraftRecordAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

}